<?php
/**
 * Created by PhpStorm.
 * User: jackie
 * Date: 2021/12/15
 * Time: 17:31
 */

namespace app\api\services;


use think\Db;

class ProxyIpPondService
{

    public static function shenlong_redis()
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->select(2);

        $config = self::getBaoGuangProxyConfig();
        if (!$config) {
            return false;
        }

        $space_s = $config['config']['space_s'];//间隔时间
        $extract = $config['config']['extract'];//提取数量
        $queue_len = $config['config']['queue_len'];//队列长度
        $expire_time = $config['config']['expire_time'];//增加IP过期时间
        if (!$extract || !$space_s || !$queue_len || !$expire_time) {
            return false;
        }

        $len = round(60 / $space_s);
        for ($i = 0; $i < $len; $i++) {
            if ($redis->lLen('ProxyIpList') <= $queue_len) { //队列维护长度在 16
                $ps = [];
                $proxyList = [];
                foreach ($config['list'] as $item) {
                    if ($redis->get('ProxyIpNum:' . $item['from']) >= $item['num']) {
                        continue;
                    }
                    $ps[$item['id']] = $item['num'];
                    $proxyList[$item['id']] = $item;
                }
                if (empty($ps)) {
                    continue;
                }
                $listId = self::random($ps);

                $url = $proxyList[$listId]['proxy_url'] . $extract;
                $from = $proxyList[$listId]['from'];


                echo date('Y-m-d H:i:s', time()) . '-';

                $res = curl_get($url);
                $data = json_decode($res,true);

                if (($from == 'shenlong' && $data['code'] == 200) || ($from == 'tianqi' && $data['code'] == 1000) || ($from == 'tianqi_linshi' && $data['code'] == 1000)) {
                    $res = $data['data'];
                    if ($redis->exists('ProxyIpNum:' . $from)) {
                        $redis->incrBy('ProxyIpNum:' . $from, $extract);
                    } else {
                        $Rexpire_time = strtotime(date('Y-m-d 23:59:59', time())) - time();
                        $redis->setex('ProxyIpNum:' . $from, $Rexpire_time, $extract);
                    }
                    foreach ($res as $item) {
                        $item['time'] = time() + $expire_time;//设定过期时间为1分钟
                        $item['user'] = $proxyList[$listId]['user_name'];
                        $item['password'] = $proxyList[$listId]['password'];
                        $item['from'] = $proxyList[$listId]['from'];
                        $redis->rpush('ProxyIpList', json_encode($item));

                        $datas['ip'] = $item['ip'];
                        $datas['expire_time'] = $item['time'];
                        $datas['from'] = $item['from'];
                        $datas['ip_str'] = json_encode($item);
                        $datas['collect_time'] = time();
                        $datas['create_time'] = date('Y-m-d H:i:s');
                        $datas['status'] = 3;
                        Db::name('ip_logs')->insert($datas);
                    }

                } else {
                    echo $res;
                    die;
                }
                echo "success\r\n";
            } else {
                echo "----队列长度大于'.$queue_len.'，不用更新--------\r\n";
            }
            sleep($space_s);
        }

    }

    private static function getBaoGuangProxyConfig()
    {
        $type = Db::name('params_type')->where('name', '=', 'baoguang')->field('id')->find();
        $typeid = !empty($type) ? $type['id'] : 0;
        $list = Db::name('proxy_list')->where('type_id', $typeid)->select();
        if (empty($list)) {
            return false;
        }
        $time_hhiiss = date('H:i:s', time());
        $sql1 = "SELECT * FROM `fa_proxy_config` WHERE type_id =" . $typeid . "  AND `start_time` <= '" . $time_hhiiss . "'  AND `end_time` > '" . $time_hhiiss . "';";
        $result = Db::query($sql1);
        if (!$result) {
            return false;
        }
        return [
            'list' => $list,
            'config' => $result[0]
        ];
    }

    private static function random($ps)
    {
        static $arr = array();
        $key = md5(serialize($ps));

        if (!isset($arr[$key])) {
            $max = array_sum($ps);
            foreach ($ps as $k => $v) {
                $v = $v / $max * 10000;
                for ($i = 0; $i < $v; $i++) $arr[$key][] = $k;
            }
        }
        return $arr[$key][mt_rand(0, count($arr[$key]) - 1)];
    }
}
